import { LogHelper } from "../utils/logHelper"

/**
 * 房间防御检查
 */
export class DefenseRoomTask implements IRoomTask{
  run(room: Room): void {

    // 如果房间不是我的，并且不是外矿房间，不触发防御条件
    if(!room.my()){
      // 判断是否外矿房间
      const outRooms = Object.values(Memory.rooms).filter((r)=> r.claimers && r.claimers.indexOf(room.name) > -1);
      if(outRooms.length === 0){
        return;
      }
    }

    // 查看房间列表敌人是否还存在
    const role = 'defender';
    if(room.memory.enemys){
      for(const id of room.memory.enemys){
        var enemy = Game.getObjectById(id) as Creep;
        if(enemy) {
          // 敌人还存在
          let defendersCount = 10;
          const defenders = room.find(FIND_MY_CREEPS)
            .filter((creep) => creep.memory.role === role && (!creep.memory.attackTarget || creep.memory.attackTarget === id));
          for(var defender of defenders){
            // 把所有防御者设为攻击他
            defender.memory.attackTarget = id;
          }
          if(defenders.length < defendersCount){
            for (let index = 0; index < (defendersCount - defenders.length); index++) {
              const body:BodyPartConstant[] = [TOUGH,MOVE,HEAL,ATTACK];//蝗虫攻击法
              room.spawnQueueAdd(role,body,{ role, bornRoom:room.name, attackTarget:id});
              LogHelper.log(`防御房间管理[${room.name}] 申请孵化 ${role}`);
            }
          }
        }
        else {
          // 删除掉所需要孵化的 防御者
          const queueCreeps = room.spawnQueueGetRole(role,(creeps) => creeps.memory.attackTarget !== undefined && creeps.memory.attackTarget === id);
          queueCreeps.forEach((creep)=>{
            room.spawnQueueRemove(creep);
            LogHelper.log(`防御房间管理[${room.name}] 敌人 id ${id} 已清除，将多余的防御者孵化移出队列`);
          });
          // 如果没在房间内了把他从敌人名单移除
          room.memory.enemys.splice(room.memory.enemys.indexOf(id),1);
        }
      }
    }
  }
}